package com.peng.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import com.peng.pojo.User;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

@Configuration
public class ShiroConfig {

    //ShiroFilterFactoryBean
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("getDefaultWebSecurityManager") DefaultWebSecurityManager defaultWebSecurityManager) {
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        bean.setSecurityManager(defaultWebSecurityManager);
            //添加shiro的内置过滤器
        /**
         anon:无需认证就可以访问
         authc:必须认证才可访问
         user：必须拥有   记住我才能用
         perms：拥有对某个资源的权限才能访问
         role:拥有某个角色权限才能访问
         **/
        HashMap<String, String> objectObjectHashMap = new HashMap<>();
        objectObjectHashMap.put("/user/add", "perms[user:add]");
        objectObjectHashMap.put("/user/update", "perms[user:update]");
//        objectObjectHashMap.put("/user/**","perms[user:all]");

        objectObjectHashMap.put("/user/*", "authc");

        bean.setFilterChainDefinitionMap(objectObjectHashMap);

        //设置登录请求
        bean.setLoginUrl("/toLogin");
        //设置无权限的跳转页面
        bean.setUnauthorizedUrl("/noauth");

        return bean;
    }

    //DefaultWebSecurityManager
    @Bean
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("getUserShiro") UserShiro userShiro) {
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        defaultWebSecurityManager.setRealm(userShiro);
        return defaultWebSecurityManager;
    }

    //创建Realm
    @Bean
    public UserShiro getUserShiro() {
        return new UserShiro();
    }

    //用来整合thymeleaf 和 shiro
    @Bean
    public ShiroDialect shiroDialect() {
        return new ShiroDialect();
    }

}
